package com.education.ai.controller;

import com.education.ai.entity.TeachingPlan;
import com.education.ai.service.TeachingPlanService;
import com.education.ai.util.TeacherContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api/teaching-plans")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true", exposedHeaders = "X-Total-Count")
public class TeachingPlanController {

    @Autowired
    private TeachingPlanService teachingPlanService;

    @PersistenceContext
    private EntityManager entityManager;

    @GetMapping
    public ResponseEntity<List<TeachingPlan>> getAllTeachingPlans(
            @RequestParam(required = false) String teacherId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "15") int size,
            HttpServletRequest request) {
        // 增强日志记录 - 详细记录请求参数和上下文
        log.info("获取教学计划列表，教师ID：{}，页码：{}，每页数量：{}", teacherId, page, size);

        // 记录请求头信息，帮助调试前端传递的参数
        log.info("请求头Origin: {}", request.getHeader("Origin"));
        log.info("请求头Referer: {}", request.getHeader("Referer"));

        // 检查字符串"undefined"，这是前端localStorage存储错误导致的特殊情况
        if (teacherId != null && ("undefined".equals(teacherId) || "null".equals(teacherId))) {
            log.warn("检测到特殊的教师ID值: [{}]，这可能是前端localStorage存储错误导致的", teacherId);
            teacherId = null; // 重置为null，后续将使用请求属性或上下文中的教师ID
        }

        // 从请求属性中获取教师ID，检查是否与参数一致
        String attrTeacherId = (String) request.getAttribute("teacherId");
        if (attrTeacherId != null && !attrTeacherId.equals(teacherId)) {
            log.warn("请求参数中的教师ID[{}]与请求属性中的教师ID[{}]不一致", teacherId, attrTeacherId);
            // 如果参数中没有teacherId但请求属性中有，则使用属性中的教师ID
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = attrTeacherId;
                log.info("使用请求属性中的教师ID: {}", teacherId);
            }
        }

        // 尝试从TeacherContext获取教师ID
        String contextTeacherId = TeacherContext.getCurrentTeacherId();
        if (contextTeacherId != null) {
            log.info("从TeacherContext获取到教师ID: {}", contextTeacherId);
            // 如果参数和属性都没有教师ID但上下文有，则使用上下文中的教师ID
            if ((teacherId == null || teacherId.isEmpty()) && (attrTeacherId == null || attrTeacherId.isEmpty())) {
                teacherId = contextTeacherId;
                log.info("使用TeacherContext中的教师ID: {}", teacherId);
            }
        }

        log.info("开始根据教师ID[{}]查询教学计划", teacherId);

        // 如果教师ID为空，则返回空列表
        if (teacherId == null || teacherId.isEmpty()) {
            log.warn("教师ID为空，无法查询教学计划");
            return ResponseEntity.ok(new ArrayList<>());
        }

        try {
            List<TeachingPlan> plans;
            long total;

            if ("all".equals(teacherId)) {
                // 查询所有教学计划
                plans = teachingPlanService.findAll(PageRequest.of(page, size));
                total = teachingPlanService.count();
            } else {
                // 根据教师ID查询教学计划
                plans = teachingPlanService.findByTeacherId(teacherId, PageRequest.of(page, size));
                total = teachingPlanService.countByTeacherId(teacherId);
            }

            log.info("查询结果: 返回了{}条记录，总记录数：{}", plans.size(), total);

            // 如果没有查询到记录，尝试使用原生SQL查询
            if (plans.isEmpty()) {
                log.warn("未查询到教师ID为[{}]的教学计划记录，尝试使用原生SQL查询", teacherId);
                try {
                    // 使用EntityManager执行原生SQL查询
                    List<TeachingPlan> sqlPlans = entityManager.createNativeQuery(
                                    "SELECT * FROM teaching_plans WHERE teacher_id = ?1 ORDER BY create_time DESC",
                                    TeachingPlan.class)
                            .setParameter(1, teacherId)
                            .getResultList();

                    log.info("原生SQL查询结果: 返回了{}条记录", sqlPlans.size());
                    if (!sqlPlans.isEmpty()) {
                        plans = sqlPlans;
                    }
                } catch (Exception e) {
                    log.error("原生SQL查询失败", e);
                }
            }

            // 设置响应头，包含总记录数
            HttpHeaders headers = new HttpHeaders();
            headers.add("X-Total-Count", String.valueOf(total));

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(plans);
        } catch (Exception e) {
            log.error("查询教学计划时发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<TeachingPlan> getTeachingPlanById(@PathVariable Long id) {
        log.info("获取教学计划详情，ID: {}", id);
        return ResponseEntity.ok(teachingPlanService.findById(id));
    }

    @GetMapping("/subject/{subject}")
    public ResponseEntity<List<TeachingPlan>> getTeachingPlansBySubject(@PathVariable String subject) {
        log.info("获取学科教学计划列表: {}", subject);
        return ResponseEntity.ok(teachingPlanService.findBySubject(subject));
    }

    @GetMapping("/grade/{grade}")
    public ResponseEntity<List<TeachingPlan>> getTeachingPlansByGrade(@PathVariable String grade) {
        log.info("获取年级教学计划列表: {}", grade);
        return ResponseEntity.ok(teachingPlanService.findByGrade(grade));
    }

    @PostMapping
    public ResponseEntity<TeachingPlan> saveTeachingPlan(@RequestBody TeachingPlan teachingPlan) {
        log.info("保存教学计划: {}", teachingPlan.getTitle());
        return ResponseEntity.ok(teachingPlanService.save(teachingPlan));
    }

    @PutMapping("/{id}")
    public ResponseEntity<TeachingPlan> updateTeachingPlan(@PathVariable Long id, @RequestBody TeachingPlan teachingPlan) {
        log.info("更新教学计划，ID: {}", id);
        teachingPlan.setId(id);
        return ResponseEntity.ok(teachingPlanService.save(teachingPlan));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTeachingPlan(@PathVariable Long id) {
        log.info("删除教学计划，ID: {}", id);
        teachingPlanService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 保存前端设计的教学计划
     */
    @PostMapping("/save-design")
    public ResponseEntity<TeachingPlan> saveDesignedTeachingPlan(
            @RequestParam String subject,
            @RequestParam String grade,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String teacherId,
            @RequestBody String content) {
        log.info("保存前端设计的教学计划 - 学科: {}, 年级: {}, 教师ID: {}", subject, grade, teacherId);

        TeachingPlan plan = new TeachingPlan();
        plan.setSubject(subject);
        plan.setGrade(grade);
        plan.setTitle(title != null ? title : String.format("%s%s - 教学设计", grade, subject));
        plan.setContent(content);
        plan.setDuration(45); // 默认45分钟

        // 设置教师ID
        if (teacherId != null && !teacherId.isEmpty()) {
            plan.setTeacherId(teacherId);
        }

        return ResponseEntity.ok(teachingPlanService.save(plan));
    }

    /**
     * 获取模板教学计划
     */
    @GetMapping("/templates")
    public ResponseEntity<List<TeachingPlan>> getTeachingPlanTemplates() {
        log.info("获取教学计划模板列表");
        return ResponseEntity.ok(teachingPlanService.findTemplates());
    }

    /**
     * 调试端点：检查数据库中的教师教学计划记录
     */
    @GetMapping("/debug")
    public ResponseEntity<?> debugTeacherPlans(
            @RequestParam String teacherId) {
        try {
            log.info("调试: 直接从数据库查询教师[{}]的教学计划记录", teacherId);

            // 使用Repository直接查询
            List<TeachingPlan> plans = teachingPlanService.findByTeacherId(teacherId);
            log.info("教师[{}]的教学计划数量: {}", teacherId, plans.size());

            if (plans.isEmpty()) {
                log.warn("数据库中没有找到教师[{}]的教学计划记录", teacherId);

                // 查询数据库中的所有教学计划
                List<TeachingPlan> allPlans = teachingPlanService.findAll();
                log.info("数据库中共有{}条教学计划记录", allPlans.size());

                // 输出每条记录的teacherId
                for (TeachingPlan plan : allPlans) {
                    log.info("教学计划[{}] 教师ID: {}", plan.getId(), plan.getTeacherId());
                }
            } else {
                // 输出查询到的记录详情
                for (TeachingPlan plan : plans) {
                    log.info("找到教学计划: ID={}, 标题={}, 教师ID={}, 创建时间={}",
                            plan.getId(), plan.getTitle(), plan.getTeacherId(), plan.getCreateTime());
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "教师ID: " + teacherId + ", 查询到记录数: " + plans.size());
            result.put("data", plans);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("调试查询失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("调试查询失败: " + e.getMessage());
        }
    }

    /**
     * 调试端点：使用原生SQL查询检查数据库
     */
    @GetMapping("/sql-debug")
    public ResponseEntity<?> sqlDebug(@RequestParam String teacherId) {
        try {
            log.info("执行原生SQL查询，检查教师[{}]的教学计划记录", teacherId);

            Map<String, Object> result = new HashMap<>();

            // 1. 查询表结构
            log.info("查询teaching_plans表结构");
            try {
                List<Object[]> columns = entityManager.createNativeQuery(
                        "SHOW COLUMNS FROM teaching_plans").getResultList();
                List<Map<String, Object>> columnInfo = new ArrayList<>();
                for (Object[] column : columns) {
                    Map<String, Object> col = new HashMap<>();
                    col.put("name", column[0]);
                    col.put("type", column[1]);
                    columnInfo.add(col);
                }
                result.put("tableStructure", columnInfo);
            } catch (Exception e) {
                log.error("查询表结构失败", e);
                result.put("tableStructureError", e.getMessage());
            }

            // 2. 直接使用SQL查询教师ID的记录
            log.info("使用SQL直接查询教师[{}]的记录", teacherId);
            try {
                List<Object[]> records = entityManager.createNativeQuery(
                                "SELECT id, title, teacher_id, create_time FROM teaching_plans WHERE teacher_id = ?")
                        .setParameter(1, teacherId)
                        .getResultList();

                List<Map<String, Object>> recordsList = new ArrayList<>();
                for (Object[] record : records) {
                    Map<String, Object> rec = new HashMap<>();
                    rec.put("id", record[0]);
                    rec.put("title", record[1]);
                    rec.put("teacher_id", record[2]);
                    rec.put("create_time", record[3]);
                    recordsList.add(rec);
                }
                result.put("records", recordsList);
                result.put("recordCount", records.size());
            } catch (Exception e) {
                log.error("SQL查询记录失败", e);
                result.put("recordsError", e.getMessage());
            }

            // 3. 查询所有记录的teacher_id
            log.info("查询所有教学计划记录的teacher_id");
            try {
                List<Object[]> allTeacherIds = entityManager.createNativeQuery(
                                "SELECT id, title, teacher_id FROM teaching_plans")
                        .getResultList();

                List<Map<String, Object>> teacherIdsList = new ArrayList<>();
                for (Object[] record : allTeacherIds) {
                    Map<String, Object> rec = new HashMap<>();
                    rec.put("id", record[0]);
                    rec.put("title", record[1]);
                    rec.put("teacher_id", record[2]);
                    teacherIdsList.add(rec);
                }
                result.put("allTeacherIds", teacherIdsList);
                result.put("totalRecords", allTeacherIds.size());
            } catch (Exception e) {
                log.error("查询所有teacher_id失败", e);
                result.put("allTeacherIdsError", e.getMessage());
            }

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("SQL调试查询失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("SQL调试查询失败: " + e.getMessage());
        }
    }

    /**
     * 调试端点：查看所有教学计划记录
     */
    @GetMapping("/all-debug")
    public ResponseEntity<?> allRecordsDebug() {
        try {
            log.info("查询所有教学计划记录");

            List<TeachingPlan> allPlans = teachingPlanService.findAll();
            log.info("总共找到{}条记录", allPlans.size());

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", allPlans);
            result.put("count", allPlans.size());

            // 打印每条记录的教师ID
            for (TeachingPlan plan : allPlans) {
                log.info("教学计划ID: {}, 标题: {}, 教师ID: {}",
                        plan.getId(), plan.getTitle(), plan.getTeacherId());
            }

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询所有记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("查询失败: " + e.getMessage());
        }
    }
} 